package cn.xfdtool.slowsql;

import cn.xfdtool.slowsql.config.SlowSQLConfig;
import cn.xfdtool.slowsql.interceptor.SlowSQLInterceptor;
import cn.xfdtool.slowsql.processor.SlowSQLProcessor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * 初始化加载器
 * @author xfd
 * 2022/5/14
 */
@Slf4j
public class SQLSessionBeanPostProcessor implements BeanPostProcessor {

    @Autowired
    private SlowSQLConfig slowSQLConfig;

    @Autowired
    private SlowSQLProcessor slowSQLProcessor;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof SqlSessionFactory) {
            initMyBatis((SqlSessionFactory)bean);
        }
        if (bean instanceof SqlSessionTemplate) {
            initMyBatis(((SqlSessionTemplate)bean).getSqlSessionFactory());
        }
        return bean;
    }
    /**
     * 初始化拦截器
     * @param sqlSessionFactory
     */
    protected void initMyBatis(SqlSessionFactory sqlSessionFactory) {
        if (!this.slowSQLConfig.isEnable()) {
            log.info("slowsql interceptor disabled.");
            return;
        }
        log.info("slowsql interceptor enable datasource [{}] start.", sqlSessionFactory.getConfiguration().getEnvironment().getId());
        sqlSessionFactory.getConfiguration().addInterceptor(new SlowSQLInterceptor(this.slowSQLProcessor));
        log.info("slowsql interceptor enable datasource [{}] end.", sqlSessionFactory.getConfiguration().getEnvironment().getId());
    }
}
